package com.ac.scum.log.web.model.wechat.pay.controller;

import com.ac.scum.log.web.model.wechat.pay.service.PayService;
import com.alibaba.fastjson2.JSON;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.core.notification.NotificationConfig;
import com.wechat.pay.java.core.notification.NotificationParser;
import com.wechat.pay.java.core.notification.RequestParam;
import com.wechat.pay.java.service.partnerpayments.app.model.Transaction;
import jakarta.servlet.http.HttpServletRequest;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import static com.ac.scum.log.web.model.wechat.pay.service.PayService.*;

@Slf4j
@RestController
@RequestMapping("/wechat/pay")
@AllArgsConstructor
public class CallBackController {

    private final PayService payService;

    @PostMapping("notify")
    public Map<String, String> payNotify(HttpServletRequest request, @RequestBody Map<String, Object> body) {
        log.info("接收微信通知：");
        String signature = request.getHeader("Wechatpay-Signature");
        String timestamp = request.getHeader("Wechatpay-Timestamp");
        String signType = request.getHeader("Wechatpay-Signature-Type");
        String serial = request.getHeader("Wechatpay-Serial");
        String nonce = request.getHeader("Wechatpay-Nonce");
        log.info("===================================================：");
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String element = headerNames.nextElement();
            System.out.println(element + ":" + request.getHeader(element));
        }
        RequestParam requestParam = new RequestParam.Builder()
                .serialNumber(serial)
                .nonce(nonce)
                .signature(signature)
                .timestamp(timestamp)
                .signType(signType)
                .body(JSON.toJSONString(body))
                .build();

        NotificationConfig rsaNotificationConfig = new RSAAutoCertificateConfig.Builder()
                .merchantId(merchantId)
                .privateKeyFromPath(localPrivateKeyPath)
                .merchantSerialNumber(merchantSerialNumber)
                .apiV3Key(apiV3Key)
                .build();


        // 初始化 NotificationParser
        NotificationParser parser = new NotificationParser(rsaNotificationConfig);

        try {
            switch ((String) body.getOrDefault("event_type", "")) {
                case "TRANSACTION.SUCCESS": // 支付通知
                    Transaction decryptObject = parser.parse(requestParam, Transaction.class);
                    payService.paySuccess(decryptObject);
                    break;
                case "REFUND.SUCCESS": // 退款成功通知
                case "REFUND.ABNORMAL": // 退款异常通知
                case "REFUND.CLOSED": // 退款关闭通知
                    break;
            }
        } catch (Exception e) {
            log.error("微信通知接受解密处理发生异常", e);
            Map<String, String> res = new HashMap<>();
            res.put("code", "FAIL");
            res.put("message", e.getMessage());
            return res;
        }
        Map<String, String> res = new HashMap<>();
        res.put("code", "SUCCESS");
        res.put("message", "成功");
        return res;
    }
}
